package com.kuang.linkedlist;

/*将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。*/

/**
 * @author kjx
 */
public class MergeTwoList {


    //这种解法很通用，不多废话了
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        //设置一个头节点用于保存、尾节点用于跟踪
        ListNode hail = new ListNode();
        ListNode resultNode = hail;
        //正式循环
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                hail.next = list1;
                list1 = list1.next;
            } else {
                hail.next = list2;
                list2 = list2.next;
            }
            hail = hail.next;
        }
        //接上剩余的list
        if (list1 != null) hail.next = list1;
        if (list2 != null) hail.next = list2;

        return resultNode.next;
    }


    //我们来看看递归的解法
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        if (list1.val <= list2.val) {
            list1.next = mergeTwoLists2(list1.next, list2);
            return list1;
        }
        list2.next = mergeTwoLists2(list1,list2.next);
        return list2;
    }

}
